package com.wei.service.impl;

import com.wei.blog.common.constants.FollowerConstants;
import com.wei.entity.UserEntity;
import com.wei.service.IFollowerService;
import com.wei.service.UserService;
import com.wei.vo.FollowerVo;
import com.wei.vo.UserToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class FollowerServiceImpl implements IFollowerService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    @Override
    public void click(Integer fid, Integer uid) {
        //关注 取消关注
        //你关注了对方 你成为了对方的粉丝
        redisTemplate.execute(new SessionCallback() {
            @Override
            public Object execute(RedisOperations operations) throws DataAccessException {
                // 创建两个key
                String followerKey = String.format(FollowerConstants.FOLLOWER_KEY, uid);
                String fansKey = String.format(FollowerConstants.FANS_KEY, fid);
                //查询是否关注过对方
                Double time = redisTemplate.opsForZSet().score(followerKey, fid);

                //开启事务
                operations.multi();
                if (time == null) {
                    System.out.println("进入添加键的操作");
                    //如果用户未关注过对方，则增加关注数量 redis产生两条数据
                    //存入关注的时间 （后面查看列表可以根据时间排列显示）
                    redisTemplate.opsForZSet().add(followerKey, fid, System.currentTimeMillis());
                    //存入粉丝关系
                    redisTemplate.opsForZSet().add(fansKey, uid, System.currentTimeMillis());
                } else {
                    //如果用户已经关注 删除对应的两条记录
                    //System.out.println("进入删除键的操作");
                    Long remove1 = redisTemplate.opsForZSet().remove(followerKey, fid);
                    Long remove2 = redisTemplate.opsForZSet().remove(fansKey, uid);
                }
                //事务提交
                operations.exec();
                return null;
            }
        });
    }

    @Override
    public Boolean findUserFollowerStatus(Integer fid, Integer uid) {
        //返回是否关注过对方
        String followerKey = String.format(FollowerConstants.FOLLOWER_KEY, uid);
        Double time = redisTemplate.opsForZSet().score(followerKey, fid);
        return  time!= null ? true : false;
    }

    @Override
    public Long findUserFollowerCount(Integer userId) {
        String followerKey = String.format(FollowerConstants.FOLLOWER_KEY, userId);
        return redisTemplate.opsForZSet().size(followerKey);
    }

    @Override
    public long findUserFansCount(Integer userId) {
        String fansKey = String.format(FollowerConstants.FANS_KEY, userId);
        return redisTemplate.opsForZSet().size(fansKey);
    }

    @Override
    public List<FollowerVo> findFollowerListByUserId(Integer userId, Integer type) {
        //创建一个列表 存放关注人信息
        List<FollowerVo> list = new ArrayList<>();
        //redis中存入 用户id
        //刻意根据用户id 把其他信息查出来
        String key = null;
        if (type == 1) {
            key = String.format(FollowerConstants.FOLLOWER_KEY, userId);
        } else {
            key = String.format(FollowerConstants.FANS_KEY, userId);
        }
        //查询搜有结果
        Set set = redisTemplate.opsForZSet().range(key, 0, -1);
        //循环集合 通过用户id每个用户的信息
        //创建一个迭代器
        Iterator iterator = set.iterator();
        //iterator.hasNext() 判断集合是否存在下一条记录
        //如果存在下一条记录 接着循环 否则 终止循环
        while (iterator.hasNext()) {
            //获取对方id
            Integer uid = (Integer) iterator.next();
            //关注时间
            Double time = redisTemplate.opsForZSet().score(key, uid);
            //查询用户信息
            UserEntity userEntity = userService.findUserById(uid);
            //把查询到的用户信息 填入到 FollowerVo中
            FollowerVo followerVo = new FollowerVo();
            followerVo.setUserId(userEntity.getId());
            followerVo.setUsername(userEntity.getUsername());
            followerVo.setCreateTime(new Date(time.longValue()));
            followerVo.setHeadUrl(userEntity.getHeadUrl());
            list.add(followerVo);
        }
        return list;
    }
    }


